<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel导出示例</title>
    <script src="./js/polyfill.js"></script>
    <script src="./js/exceljs.js"></script>
    <script src="js/vue.js"></script>
</head>

<body>
    <div id="app">
        <h1>{{title}}</h1>
        <button @click="generateExcel()">Generate Excel</button>
    </div>

    <script>
        var vue = new Vue({
            el: '#app',
            data: {
                title: 'Excel导出演示'
            },
            methods: {
                async generateExcel() {
                    // 1. 创建工作簿
                    const workbook = new ExcelJS.Workbook();
                    workbook.creator = '系统自动生成';
                    workbook.lastModifiedBy = '用户';
                    workbook.created = new Date();
                    workbook.modified = new Date();

                    // 2. 添加工作表
                    const worksheet = workbook.addWorksheet('销售数据', {
                        properties: { tabColor: { argb: 'FFC0000' } } // 红色标签
                    });

                    // 3. 设置列定义
                    worksheet.columns = [
                        {
                            header: '订单号', key: 'id', width: 20
                        },
                        { header: '金额', key: 'amount', width: 15, style: { numFmt: '¥#,##0.00' } },
                        { header: '日期', key: 'date', width: 15, style: { numFmt: 'yyyy-mm-dd' } }
                    ];

                    // 4. 添加数据行（可以添加多条数据）
                    worksheet.addRow({ id: 'ORD-20230001', amount: 1999.9, date: new Date() });
                    worksheet.addRow({ id: 'ORD-20230001', amount: 2599.5, date: new Date() });
                    worksheet.addRow({ id: 'ORD-20230001', amount: 999, date: new Date() });
                    console.log(worksheet);
                    worksheet['_rows'][0]['_cells'][0]['style'] = {
                        fill: {
                            type: 'pattern',
                            pattern: 'solid',
                            fgColor: { argb: 'FF4472C4' }
                        }
                    };
                    // worksheet.mergeCells('A2:A4'); 合并单元格
                    // 5. 关键步骤：生成文件并下载
                    try {
                        // 生成二进制文件内容（使用xlsx格式）
                        const buffer = await workbook.xlsx.writeBuffer();

                        // 转换为Blob对象
                        const blob = new Blob([buffer], {
                            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                        });

                        // 创建下载链接
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = '销售数据_' + new Date().toLocaleDateString() + '.xlsx'; // 文件名
                        document.body.appendChild(a);

                        // 触发下载
                        a.click();

                        // 清理资源
                        setTimeout(() => {
                            document.body.removeChild(a);
                            window.URL.revokeObjectURL(url);
                        }, 0);

                        console.log('Excel导出成功');
                    } catch (error) {
                        console.error('导出失败:', error);
                        alert('导出Excel时发生错误，请重试');
                    }
                }
            },
        });
    </script>
</body>

</html>